# -*- coding: utf-8 -*-
"""
操作系统账号管理模块
"""

from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QTableWidget, 
                            QTableWidgetItem, QPushButton, QLineEdit, QLabel, 
                            QMessageBox, QDialog, QFormLayout, QDialogButtonBox, QComboBox)
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QFont
from models import OSAccountModel
from database import Database

class OSAccountManagementWidget(QWidget):
    def __init__(self):
        super().__init__()
        self.model = OSAccountModel()
        self.db = Database()
        self.init_ui()
        self.load_data()
    
    def init_ui(self):
        """初始化用户界面"""
        layout = QVBoxLayout(self)
        layout.setContentsMargins(10, 10, 10, 10)
        layout.setSpacing(15)
        
        # 搜索栏
        search_frame = QWidget()
        search_frame.setStyleSheet("""
            QWidget {
                background-color: #ffffff;
                border: 1px solid #e9ecef;
                border-radius: 8px;
                padding: 15px;
            }
        """)
        search_layout = QHBoxLayout(search_frame)
        search_layout.setContentsMargins(20, 15, 20, 15)
        search_layout.setSpacing(20)
        
        search_label = QLabel("🔍 搜索:")
        search_label.setStyleSheet("font-weight: 600; color: #495057; font-size: 14px;")
        
        self.search_input = QLineEdit()
        self.search_input.setPlaceholderText("输入账户名称、级别或类型...")
        self.search_input.textChanged.connect(self.search_data)
        self.search_input.setStyleSheet("""
            QLineEdit {
                border: 2px solid #e9ecef;
                border-radius: 6px;
                padding: 10px 15px;
                font-size: 14px;
                background-color: #f8f9fa;
                min-width: 300px;
            }
            QLineEdit:focus {
                border: 2px solid #4a90e2;
                background-color: #ffffff;
            }
        """)
        
        search_layout.addWidget(search_label)
        search_layout.addWidget(self.search_input)
        search_layout.addStretch()
        
        # 操作按钮
        self.add_button = QPushButton("➕ 添加账号")
        self.add_button.clicked.connect(self.add_os_account)
        self.add_button.setStyleSheet("""
            QPushButton {
                background-color: #28a745;
                color: white;
                border: none;
                border-radius: 6px;
                padding: 10px 20px;
                font-size: 14px;
                font-weight: 600;
            }
            QPushButton:hover {
                background-color: #218838;
            }
            QPushButton:pressed {
                background-color: #1e7e34;
            }
        """)
        
        self.edit_button = QPushButton("✏️ 编辑账号")
        self.edit_button.clicked.connect(self.edit_os_account)
        self.edit_button.setStyleSheet("""
            QPushButton {
                background-color: #ffc107;
                color: #212529;
                border: none;
                border-radius: 6px;
                padding: 10px 20px;
                font-size: 14px;
                font-weight: 600;
            }
            QPushButton:hover {
                background-color: #e0a800;
            }
            QPushButton:pressed {
                background-color: #d39e00;
            }
        """)
        
        self.delete_button = QPushButton("🗑️ 删除账号")
        self.delete_button.clicked.connect(self.delete_os_account)
        self.delete_button.setStyleSheet("""
            QPushButton {
                background-color: #dc3545;
                color: white;
                border: none;
                border-radius: 6px;
                padding: 10px 20px;
                font-size: 14px;
                font-weight: 600;
            }
            QPushButton:hover {
                background-color: #c82333;
            }
            QPushButton:pressed {
                background-color: #bd2130;
            }
        """)
        
        self.refresh_button = QPushButton("🔄 刷新")
        self.refresh_button.clicked.connect(self.load_data)
        self.refresh_button.setStyleSheet("""
            QPushButton {
                background-color: #17a2b8;
                color: white;
                border: none;
                border-radius: 6px;
                padding: 10px 20px;
                font-size: 14px;
                font-weight: 600;
            }
            QPushButton:hover {
                background-color: #138496;
            }
            QPushButton:pressed {
                background-color: #117a8b;
            }
        """)
        
        search_layout.addWidget(self.add_button)
        search_layout.addWidget(self.edit_button)
        search_layout.addWidget(self.delete_button)
        search_layout.addWidget(self.refresh_button)
        
        layout.addWidget(search_frame)
        
        # 数据表格
        self.table = QTableWidget()
        self.table.setColumnCount(5)
        self.table.setHorizontalHeaderLabels([
            "👤 账户名称", "🏆 账号级别", "🏷️ 账号类型", "🔐 账号密码", "🖥️ 关联IP"
        ])
        self.table.setSelectionBehavior(QTableWidget.SelectRows)
        self.table.setSelectionMode(QTableWidget.SingleSelection)
        self.table.setAlternatingRowColors(True)
        
        # 设置表格样式
        self.table.setStyleSheet("""
            QTableWidget {
                background-color: #ffffff;
                border: 1px solid #e9ecef;
                border-radius: 8px;
                gridline-color: #f1f3f4;
                font-size: 13px;
                selection-background-color: #e3f2fd;
            }
            QTableWidget::item {
                padding: 8px;
                border-bottom: 1px solid #f1f3f4;
            }
            QTableWidget::item:selected {
                background-color: #e3f2fd;
                color: #1976d2;
            }
            QTableWidget::item:hover {
                background-color: #f8f9fa;
            }
            QHeaderView::section {
                background-color: #f8f9fa;
                padding: 12px 10px;
                border: none;
                border-right: 1px solid #e9ecef;
                border-bottom: 2px solid #4a90e2;
                font-weight: 600;
                font-size: 13px;
                color: #495057;
            }
            QHeaderView::section:first {
                border-top-left-radius: 8px;
            }
            QHeaderView::section:last {
                border-right: none;
                border-top-right-radius: 8px;
            }
        """)
        
        # 设置列宽
        self.table.setColumnWidth(0, 120)
        self.table.setColumnWidth(1, 100)
        self.table.setColumnWidth(2, 100)
        self.table.setColumnWidth(3, 120)
        self.table.setColumnWidth(4, 120)
        
        # 设置表头字体
        header = self.table.horizontalHeader()
        header.setFont(QFont("Microsoft YaHei", 10, QFont.Bold))
        
        layout.addWidget(self.table)
    
    def load_data(self):
        """加载数据"""
        try:
            data = self.model.get_all_os_accounts()
            self.populate_table(data)
        except Exception as e:
            QMessageBox.critical(self, "错误", f"加载数据失败：{str(e)}")
    
    def populate_table(self, data):
        """填充表格数据"""
        self.table.setRowCount(len(data))
        
        for row, item in enumerate(data):
            self.table.setItem(row, 0, QTableWidgetItem(item['account_name']))
            self.table.setItem(row, 1, QTableWidgetItem(item['account_level']))
            self.table.setItem(row, 2, QTableWidgetItem(item['account_type']))
            self.table.setItem(row, 3, QTableWidgetItem(item['account_password'] or ""))
            self.table.setItem(row, 4, QTableWidgetItem(item['associated_ip'] or ""))
            
            # 存储ID用于编辑和删除
            self.table.item(row, 0).setData(Qt.UserRole, item['id'])
    
    def search_data(self):
        """搜索数据"""
        keyword = self.search_input.text().strip()
        if keyword:
            try:
                data = self.model.search_os_accounts(keyword)
                self.populate_table(data)
            except Exception as e:
                QMessageBox.critical(self, "错误", f"搜索失败：{str(e)}")
        else:
            self.load_data()
    
    def add_os_account(self):
        """添加系统账号"""
        dialog = OSAccountDialog(self, self.db)
        if dialog.exec_() == QDialog.Accepted:
            self.load_data()
    
    def edit_os_account(self):
        """编辑系统账号"""
        current_row = self.table.currentRow()
        if current_row == -1:
            QMessageBox.warning(self, "警告", "请选择要编辑的记录")
            return
        
        item = self.table.item(current_row, 0)
        account_id = item.data(Qt.UserRole)
        
        dialog = OSAccountDialog(self, self.db, account_id)
        if dialog.exec_() == QDialog.Accepted:
            self.load_data()
    
    def delete_os_account(self):
        """删除系统账号"""
        current_row = self.table.currentRow()
        if current_row == -1:
            QMessageBox.warning(self, "警告", "请选择要删除的记录")
            return
        
        reply = QMessageBox.question(self, "确认", "确定要删除选中的系统账号记录吗？",
                                   QMessageBox.Yes | QMessageBox.No)
        
        if reply == QMessageBox.Yes:
            item = self.table.item(current_row, 0)
            account_id = item.data(Qt.UserRole)
            
            try:
                self.model.delete_os_account(account_id)
                self.load_data()
                QMessageBox.information(self, "成功", "系统账号记录删除成功")
            except Exception as e:
                QMessageBox.critical(self, "错误", f"删除失败：{str(e)}")

class OSAccountDialog(QDialog):
    def __init__(self, parent, db, account_id=None):
        super().__init__(parent)
        self.db = db
        self.account_id = account_id
        self.model = OSAccountModel()
        
        self.setWindowTitle("➕ 添加系统账号" if account_id is None else "✏️ 编辑系统账号")
        self.setModal(True)
        self.resize(500, 400)
        
        # 设置对话框样式
        self.setStyleSheet("""
            QDialog {
                background-color: #f8f9fa;
                font-family: "Microsoft YaHei";
            }
            QLabel {
                color: #495057;
                font-weight: 600;
                font-size: 14px;
            }
            QLineEdit, QComboBox {
                border: 2px solid #e9ecef;
                border-radius: 6px;
                padding: 10px 12px;
                font-size: 14px;
                background-color: #ffffff;
            }
            QLineEdit:focus, QComboBox:focus {
                border: 2px solid #4a90e2;
                outline: none;
            }
            QPushButton {
                background-color: #4a90e2;
                color: white;
                border: none;
                border-radius: 6px;
                padding: 10px 20px;
                font-size: 14px;
                font-weight: 600;
            }
            QPushButton:hover {
                background-color: #357abd;
            }
            QPushButton:pressed {
                background-color: #2968aa;
            }
        """)
        
        self.init_ui()
        
        if account_id:
            self.load_account_data()
    
    def init_ui(self):
        """初始化界面"""
        layout = QVBoxLayout(self)
        layout.setSpacing(15)
        layout.setContentsMargins(20, 20, 20, 20)
        
        # 标题
        title_label = QLabel("👤 系统账号信息")
        title_label.setStyleSheet("""
            QLabel {
                font-size: 18px;
                font-weight: bold;
                color: #4a90e2;
                margin-bottom: 10px;
                padding: 10px 0;
                border-bottom: 2px solid #4a90e2;
            }
        """)
        layout.addWidget(title_label)
        
        # 表单布局
        form_widget = QWidget()
        form_layout = QFormLayout(form_widget)
        form_layout.setSpacing(12)
        form_layout.setContentsMargins(10, 10, 10, 10)
        
        # 账户名称
        self.account_name_input = QLineEdit()
        self.account_name_input.setPlaceholderText("例如: root")
        form_layout.addRow("👤 账户名称*:", self.account_name_input)
        
        # 账号级别
        self.account_level_combo = QComboBox()
        account_levels = self.db.get_dictionary_values("账号级别")
        self.account_level_combo.addItems(account_levels)
        self.account_level_combo.setEditable(True)
        form_layout.addRow("🏆 账号级别*:", self.account_level_combo)
        
        # 账号类型
        self.account_type_combo = QComboBox()
        account_types = self.db.get_dictionary_values("账号类型")
        self.account_type_combo.addItems(account_types)
        self.account_type_combo.setEditable(True)
        form_layout.addRow("🏷️ 账号类型*:", self.account_type_combo)
        
        # 账号密码
        self.account_password_input = QLineEdit()
        self.account_password_input.setPlaceholderText("账号密码")
        form_layout.addRow("🔐 账号密码:", self.account_password_input)
        
        # 关联IP
        self.associated_ip_input = QLineEdit()
        self.associated_ip_input.setPlaceholderText("例如: 192.168.1.100")
        form_layout.addRow("🖥️ 关联IP:", self.associated_ip_input)
        
        layout.addWidget(form_widget)
        
        # 按钮区域
        button_layout = QHBoxLayout()
        button_layout.setSpacing(10)
        
        # 自定义按钮
        ok_button = QPushButton("✅ 确认")
        ok_button.clicked.connect(self.accept)
        ok_button.setStyleSheet("""
            QPushButton {
                background-color: #28a745;
                color: white;
                border: none;
                border-radius: 6px;
                padding: 10px 20px;
                font-size: 14px;
                font-weight: 600;
            }
            QPushButton:hover {
                background-color: #218838;
            }
            QPushButton:pressed {
                background-color: #1e7e34;
            }
        """)
        
        cancel_button = QPushButton("❌ 取消")
        cancel_button.clicked.connect(self.reject)
        cancel_button.setStyleSheet("""
            QPushButton {
                background-color: #6c757d;
                color: white;
                border: none;
                border-radius: 6px;
                padding: 10px 20px;
                font-size: 14px;
                font-weight: 600;
            }
            QPushButton:hover {
                background-color: #5a6268;
            }
            QPushButton:pressed {
                background-color: #545b62;
            }
        """)
        
        button_layout.addStretch()
        button_layout.addWidget(ok_button)
        button_layout.addWidget(cancel_button)
        
        layout.addLayout(button_layout)
    
    def load_account_data(self):
        """加载账号数据"""
        try:
            conn = self.db.get_connection()
            cursor = conn.cursor()
            cursor.execute('SELECT * FROM os_accounts WHERE id=?', (self.account_id,))
            data = cursor.fetchone()
            conn.close()
            
            if data:
                self.account_name_input.setText(data['account_name'])
                self.account_level_combo.setCurrentText(data['account_level'])
                self.account_type_combo.setCurrentText(data['account_type'])
                self.account_password_input.setText(data['account_password'] or "")
                self.associated_ip_input.setText(data['associated_ip'] or "")
                
        except Exception as e:
            QMessageBox.critical(self, "错误", f"加载数据失败：{str(e)}")
    
    def accept(self):
        """确定按钮事件"""
        # 获取表单数据
        account_name = self.account_name_input.text().strip()
        account_level = self.account_level_combo.currentText().strip()
        account_type = self.account_type_combo.currentText().strip()
        account_password = self.account_password_input.text().strip() or None
        associated_ip = self.associated_ip_input.text().strip() or None
        
        # 验证必填字段
        if not all([account_name, account_level, account_type]):
            QMessageBox.warning(self, "警告", "请填写所有必填字段")
            return
        
        try:
            if self.account_id:
                # 更新
                self.model.update_os_account(
                    self.account_id, account_name, account_level, account_type, 
                    account_password, associated_ip
                )
            else:
                # 添加
                self.model.add_os_account(
                    account_name, account_level, account_type, 
                    account_password, associated_ip
                )
            
            super().accept()
            
        except Exception as e:
            QMessageBox.critical(self, "错误", f"保存失败：{str(e)}")